// +----------------------------------------------------------------------
// | CmsWing [ 网站内容管理框架 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2115 http://www.cmswing.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: arterli <arterli@qq.com>
// +----------------------------------------------------------------------
const Segment = require('segment');
module.exports = class extends think.cmswing.center {
  /**
   * index action import Segment from 'segment';
   * @return {Promise} []
   */
  async indexAction() {
    // auto render template file index_index.html
    const qq = this.get('q');
    const q = decodeURI(qq);
    this.meta_title = '搜索';
    const hs = this.cookie('cmswing_historical_search');
    const ehs = decodeURI(hs);
    const num = 10;
    let hss = [];
    if (!think.isEmpty(hs)) {
      hss = ehs.split('|').reverse();
    }
    this.assign('hs', hss);
    // 搜索记录
    let hsq;
    if (think.isEmpty(hs)) {
      this.cookie('cmswing_historical_search', encodeURI(q));
    } else {
      if (!in_array(q, ehs.split('|'))) {
        hsq = ehs + '|' + q;
        this.cookie('cmswing_historical_search', encodeURI(hsq));
      }
    }
    // 排序
    const o = {
      id: 'DESC'
    };
    const map = { status: 5, _complex: {_logic: 'or'}};
    const typeMap = {
      '供应': 0,
      '采购': 1,
      '委托加工': 2,
      '承接加工': 3
    };
    if (!think.isEmpty(q)) {
      for (const key in typeMap) {
        if (typeMap.hasOwnProperty(key)) {
          const element = typeMap[key];
          if (key.indexOf(q) != -1) {
            if (map._complex['xinxileixing']) {
              map._complex['xinxileixing'][1].push(element);
            } else {
              map._complex['xinxileixing'] = ['IN', [element]];
            }
          }
        }
      }
      map._complex['xinxibiaoti|leirongmiaoshu|shangpingleibie|diqu'] = ['like', '%' + q + '%'];
      const data = await this.model('gongxufabu').where(map).page(this.get('page'), num).order(o).countSelect();
      this.assign('page', this.get('page') || '1');
      this.assign('list', data.data);
      this.assign('totalPages', data.totalPages);
      this.assign('count', data.count);
      return this.display('home/search_result');
    } else {
      return this.display('home/search_result');
    }
  }
};
